package com.blog.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blog.Utils.Result;
import com.blog.bean.domain.Course;
import com.blog.bean.dto.CourseDTO;
import com.blog.bean.vo.CourseVO;
import com.blog.mapper.CourseMapper;
import com.blog.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 任浩
 * @version 1.0
 */

@Slf4j
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Transactional
    @Override
    public Result add(CourseDTO courseDTO) {
        //校验课程参数
        if(courseDTO == null){
            return Result.error("课程参数不能为空");
        }
        if(courseDTO.getName() == null || "".equals(courseDTO.getName())){
            return Result.error("课程名称不能为空或为空字符串");
        }
        if(courseDTO.getCourseClassId() == null){
            return Result.error("课程类别id不能为空");
        }

        Course course = new Course();
        course.setName(courseDTO.getName());
        course.setAbout(courseDTO.getAbout());
        course.setCourseClassId(courseDTO.getCourseClassId());
        course.setUrl(courseDTO.getUrl());
        courseMapper.insert(course);

        return Result.success(course.getId());
    }


    /**
     * 根据课程分类id查询课程列表。
     * @param id
     * @return
     */
    @Override
    public Result<List> getByCourseClass(Integer id) {
        if(id == null){
            return Result.error("课程类别id不能为空");
        }

        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_class_id",id).eq("del",0);
        List<Course> courses = courseMapper.selectList(queryWrapper);

        List<CourseVO> res = courses.stream().map(item -> {
            return new CourseVO(item.getId(), item.getName(), item.getAbout(),
                    item.getCourseClassId(), item.getUrl(), item.getCreateTime());
        }).collect(Collectors.toList());

        log.info("得到的课程列表数据为: {}",res);

        return Result.success(res);
    }
}
